'use client';

import './globals.css';
import { useEffect, useState } from 'react';
import { usePathname } from 'next/navigation';
import Link from 'next/link';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [user, setUser] = useState<any>(null);
  const pathname = usePathname();

  useEffect(() => {
    // 每次路由变化都重新检查登录状态，解决“登录后仍显示登录/注册”的问题
    const token = localStorage.getItem('token');
    const userData = localStorage.getItem('user');
    const ok = Boolean(token && userData);
    setIsLoggedIn(ok);
    setUser(ok ? JSON.parse(userData as string) : null);
  }, [pathname]);

  const handleLogout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    setIsLoggedIn(false);
    setUser(null);
    window.location.href = '/';
  };

  return (
    <html lang="zh-CN">
      <body className="min-h-screen bg-gray-50">
        <nav className="bg-white shadow-sm">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex justify-between h-16">
              <div className="flex items-center">
                <Link href="/" className="text-xl font-bold text-gray-900">
                  Dream Match
                </Link>
              </div>
              <div className="flex items-center space-x-4">
                {isLoggedIn ? (
                  <>
                    <span className="text-gray-600">欢迎, {user?.username}</span>
                    <Link
                      href="/dashboard"
                      className="text-gray-600 hover:text-gray-900"
                    >
                      仪表盘
                    </Link>
                    <button
                      onClick={handleLogout}
                      className="bg-red-600 text-white px-4 py-2 rounded-md hover:bg-red-700"
                    >
                      退出登录
                    </button>
                  </>
                ) : (
                  <>
                    <Link
                      href="/login"
                      className="text-gray-600 hover:text-gray-900"
                    >
                      登录
                    </Link>
                    <Link href="/register" className="btn-primary">
                      注册
                    </Link>
                  </>
                )}
              </div>
            </div>
          </div>
        </nav>
        {children}
      </body>
    </html>
  );
}
